package com.dianrui.operation.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.SecretProtocolAdapter;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.SimpleCommonCallback;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.Packet;
import com.tbit.tbitblesdk.protocol.callback.PacketCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 盒子检测(T)
 */
public class TbitbleCommandActivity extends BaseActivity {
    private String mTitles;
    private String devices;
    private BluetoothAdapter blueadapter;
    private AMap aMap;


    @BindView(R.id.acc)
    TextView acc;
    @BindView(R.id.battery_lock)
    TextView batteryLock;
    @BindView(R.id.motor_lock)
    TextView motorLock;
    @BindView(R.id.input_imel)
    EditText inputImel;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.calendat_pulldown)
    ImageView calendatPulldown;
    @BindView(R.id.calendat_pullup)
    ImageView calendatPullup;
    @BindView(R.id.device_layout)
    LinearLayout deviceLayout;
    @BindView(R.id.top_layout)
    LinearLayout topLayout;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.mapviews)
    MapView mapviews;


    @Override
    public int getContentViewId() {
        return R.layout.activity_netcomand;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        TbitBle.initialize(TbitbleCommandActivity.this, new SecretProtocolAdapter());
        blueadapter = BluetoothAdapter.getDefaultAdapter();
        if (aMap == null) {
            aMap = mapviews.getMap();
        }
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("title");
                title.setText(mTitles);
            }
        }
    }


    @Override
    public void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }

    @OnClick({R.id.back, R.id.reset, R.id.sure, R.id.find_car, R.id.acc_on, R.id.acc_off, R.id.defend, R.id.undefend,  R.id.device_restart, R.id.saddle, R.id.saddle_off,
            R.id.safe_hat, R.id.scans, R.id.minus_sel, R.id.minus_add, R.id.blue_find_car, R.id.blueacc_on, R.id.blueacc_off, R.id.blue_defend, R.id.blue_undefend,
            R.id.bluedevice_restart, R.id.bluesaddle, R.id.bluesaddle_off, R.id.safe_hat_blue, R.id.voiceborrowcar, R.id.voicelowpower, R.id.voiceoutside, R.id.voiceturncar
            , R.id.voicefindcar, R.id.voicereturncar, R.id.voicewarning, R.id.voicepause, R.id.calendat_pulldown, R.id.calendat_pullup})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.find_car:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("search", "1");
                break;
            case R.id.acc_on:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("start", "2");
                break;
            case R.id.acc_off:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("stop", "3");
                break;
            case R.id.defend:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("lock", "4");
                break;
            case R.id.undefend:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("unlock", "5");
                break;

            case R.id.device_restart:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("restart", "7");
                break;
            case R.id.saddle:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("battery_unlock", "8");
                break;

            case R.id.saddle_off:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApi("battery_lock", "9");
                break;

            case R.id.safe_hat:
                sendApi("unlockHat", "10");
                break;

            case R.id.blue_find_car:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "1");
                break;
            case R.id.blueacc_on:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "2");
                break;
            case R.id.blueacc_off:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "3");
                break;
            case R.id.blue_defend:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "4");
                break;
            case R.id.blue_undefend:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "5");
                break;

            case R.id.bluedevice_restart:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "7");
                break;
            case R.id.bluesaddle:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "8");
                break;

            case R.id.bluesaddle_off:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (!blueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                    return;
                }
                connectBlueTeeth(inputImel.getText().toString(), spUtils.getString("bluedevice"), spUtils.getString("bluetoken"), "9");
                break;

            case R.id.safe_hat_blue:
                ToastUtil.showToast("暂未开放");
                break;

            case R.id.scans:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(TbitbleCommandActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent = new Intent(TbitbleCommandActivity.this, OpeationCaptureActivity.class);
                        intent.putExtra("camflag", "1");
                        startActivityForResult(intent, 102);
                    } else {
                        ActivityCompat.requestPermissions(TbitbleCommandActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent intent = new Intent(TbitbleCommandActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag", "1");
                    startActivityForResult(intent, 102);
                }
                break;
            case R.id.minus_sel:
                if (!StringUtils.isEmpty(inputImel.getText().toString())) {
                    int goodsNum = Integer.parseInt(inputImel.getText().toString().trim());
                    if (goodsNum > 1) {
                        inputImel.setText("00" + String.valueOf(goodsNum - 1));
                    }
                }
                break;

            case R.id.minus_add:
                if (!StringUtils.isEmpty(inputImel.getText().toString())) {
                    int goodsNums = Integer.parseInt(inputImel.getText().toString().trim());
                    inputImel.setText("00" + String.valueOf(goodsNums + 1));
                }
                break;

            case R.id.sure:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                TbitBle.disConnect();
                sendDeviceInfo();
                break;

            case R.id.reset:
                TbitBle.disConnect();
                inputImel.setText("");
                topLayout.setVisibility(View.GONE);
                calendatPulldown.setVisibility(View.VISIBLE);
                calendatPullup.setVisibility(View.GONE);
                deviceLayout.setVisibility(View.GONE);
                break;

            case R.id.voiceborrowcar:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "1");
                break;

            case R.id.voicelowpower:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "2");
                break;

            case R.id.voiceoutside:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "3");
                break;


            case R.id.voiceturncar:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "4");
                break;

            case R.id.voicefindcar:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "5");
                break;

            case R.id.voicereturncar:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "6");
                break;

            case R.id.voicewarning:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "7");
                break;

            case R.id.voicepause:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                sendApiVoice("voice", "8");
                break;

            case R.id.calendat_pulldown:
                calendatPulldown.setVisibility(View.GONE);
                calendatPullup.setVisibility(View.VISIBLE);
                deviceLayout.setVisibility(View.VISIBLE);
                final int measuredHeight = topLayout.getMeasuredHeight();
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollTo(0, measuredHeight);
                    }
                });
                break;

            case R.id.calendat_pullup:
                calendatPulldown.setVisibility(View.VISIBLE);
                calendatPullup.setVisibility(View.GONE);
                deviceLayout.setVisibility(View.GONE);
                break;

            default:
                break;
        }
    }


    private void sendApi(final String type, final String commandType) {
        if (!StringUtils.isEmpty(spUtils.getString("username"))) {
            if (!spUtils.getString("username").equals(inputImel.getText().toString())) {
                getDeviceCommandToken(inputImel.getText().toString());
            }
        } else {
            getDeviceCommandToken(inputImel.getText().toString());
        }
        showLoadingDialog("请稍候");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("api_type", type);
                jsonObject.addProperty("device_number", inputImel.getText().toString());
                jsonObject.addProperty("token", spUtils.getString("devicetoken"));
                jsonObject.addProperty("is_bluetooth", "0");
                XHttpRequest.getInstance().postRequest(Url.SENDAPI, jsonObject.toString(), new XHttpRequest.XCallBack() {

                    @Override
                    public void onResponse(String result) {
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                final JSONObject jsonObject = new JSONObject(result);
                                if (null != jsonObject && !isFinishing()) {
                                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    } else if ("1001".equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        getDeviceCommandToken(inputImel.getText().toString());
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    } else if ("1002".equals(jsonObject.optString("status"))) {
                                        spUtils.clear();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        JumpActivitys(LoginActivity.class);
                                        finish();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void failedRequest(String result) {
                        dismissLoadingDialog();
                        ToastUtil.showToast(getString(R.string.net_error));
                    }
                });
            }
        }, 500);

    }


    private void sendApiBlueTeeth(final String type, final String commandType) {
        if (!StringUtils.isEmpty(spUtils.getString("username"))) {
            if (!spUtils.getString("username").equals(inputImel.getText().toString())) {
                getDeviceCommandToken(inputImel.getText().toString());
            }
        } else {
            getDeviceCommandToken(inputImel.getText().toString());
        }
        showLoadingDialog("请稍候");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("api_type", type);
                jsonObject.addProperty("device_number", inputImel.getText().toString());
                jsonObject.addProperty("token", spUtils.getString("devicetoken"));
                jsonObject.addProperty("is_bluetooth", "1");
                XHttpRequest.getInstance().postRequest(Url.SENDAPI, jsonObject.toString(), new XHttpRequest.XCallBack() {

                    @Override
                    public void onResponse(String result) {
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                final JSONObject jsonObject = new JSONObject(result);
                                if (null != jsonObject && !isFinishing()) {
                                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        showLoadingDialog("正在连接蓝牙中,请稍候...");
                                    } else if ("1001".equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        getDeviceCommandToken(inputImel.getText().toString());
                                    } else if ("1002".equals(jsonObject.optString("status"))) {
                                        spUtils.clear();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        SharedUtil.setToken("");
                                        JumpActivitys(LoginActivity.class);
                                        finish();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void failedRequest(String result) {
                        dismissLoadingDialog();
                        ToastUtil.showToast(getString(R.string.net_error));
                    }
                });
            }
        }, 500);

    }


    private void sendApiVoice(final String apiType, final String type) {
        if (!StringUtils.isEmpty(spUtils.getString("username"))) {
            if (!spUtils.getString("username").equals(inputImel.getText().toString())) {
                getDeviceCommandToken(inputImel.getText().toString());
            }
        } else {
            getDeviceCommandToken(inputImel.getText().toString());
        }
        showLoadingDialog("请稍候");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("api_type", apiType);
                jsonObject.addProperty("device_number", inputImel.getText().toString());
                jsonObject.addProperty("token", spUtils.getString("devicetoken"));
                jsonObject.addProperty("type", type);
                jsonObject.addProperty("is_bluetooth", "0");
                XHttpRequest.getInstance().postRequest(Url.SENDAPI, jsonObject.toString(), new XHttpRequest.XCallBack() {

                    @Override
                    public void onResponse(String result) {
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                final JSONObject jsonObject = new JSONObject(result);
                                if (null != jsonObject && !isFinishing()) {
                                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    } else if ("1001".equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        getDeviceCommandToken(inputImel.getText().toString());
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    } else if ("1002".equals(jsonObject.optString("status"))) {
                                        spUtils.clear();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        SharedUtil.setToken("");
                                        JumpActivitys(LoginActivity.class);
                                        finish();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtil.showToast(getString(R.string.net_error));
                        }
                    }

                    @Override
                    public void failedRequest(String result) {
                        dismissLoadingDialog();
                        ToastUtil.showToast(getString(R.string.net_error));
                    }
                });
            }
        }, 500);

    }


    private void sendDeviceInfo() {
        if (!StringUtils.isEmpty(spUtils.getString("username"))) {
            if (!spUtils.getString("username").equals(inputImel.getText().toString())) {
                getDeviceCommandToken(inputImel.getText().toString());
            }
        } else {
            getDeviceCommandToken(inputImel.getText().toString());
        }
        showLoadingDialog("请稍候");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("device_number", inputImel.getText().toString());
                jsonObject.addProperty("token", spUtils.getString("devicetoken"));
                XHttpRequest.getInstance().postRequest(Url.DEVICES_INFOS, jsonObject.toString(), new XHttpRequest.XCallBack() {

                    @Override
                    public void onResponse(String result) {
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                final JSONObject jsonObject = new JSONObject(result);
                                if (null != jsonObject && !isFinishing()) {
                                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        topLayout.setVisibility(View.VISIBLE);
                                        calendatPulldown.setVisibility(View.GONE);
                                        spUtils.put("bluedevice",jsonObject.optJSONObject("data").optString("number"));
                                        spUtils.put("bluetoken",jsonObject.optJSONObject("data").optString("blue_tooth_key"));

                                        if (jsonObject.optJSONObject("data").optString("acc").equals("0")) {
                                            acc.setText("关闭");
                                        }else {
                                            acc.setText("开启");
                                        }
                                        if (jsonObject.optJSONObject("data").optString("motor_lock").equals("0")) {
                                            motorLock.setText("关闭");
                                        }else {
                                            motorLock.setText("开启");
                                        }
                                        if (jsonObject.optJSONObject("data").optString("battery_lock").equals("0")) {
                                            batteryLock.setText("关闭");
                                        }else {
                                            batteryLock.setText("开启");
                                        }


                                    } else if ("1001".equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        getDeviceCommandToken(inputImel.getText().toString());
                                        topLayout.setVisibility(View.GONE);
                                    } else if ("1002".equals(jsonObject.optString("status"))) {
                                        spUtils.clear();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        SharedUtil.setToken("");
                                        JumpActivitys(LoginActivity.class);
                                        finish();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtil.showToast(getString(R.string.net_error));
                        }
                    }

                    @Override
                    public void failedRequest(String result) {
                        dismissLoadingDialog();
                        ToastUtil.showToast(getString(R.string.net_error));
                    }
                });
            }
        }, 500);

    }
    //蓝牙连接，第一个参数暂时无用，第二个设备编号，第三个密钥，第四个作为不同功能指令区分
    private void connectBlueTeeth(final String number, String devices, String token, final String blueCommandType) {
        showLoadingDialog("正在连接蓝牙");
        TbitBle.connect(devices, token, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                if (resultCode == 0) {
                    if (blueCommandType.equals("1")) {
                        findCarBlueteethDevice();
                    } else if (blueCommandType.equals("2")) {
                        electricDoorBlueteethDevice();
                    } else if (blueCommandType.equals("3")) {
                        electricDoorCloseBlueteethDevice();
                    } else if (blueCommandType.equals("4")) {
                       defenseBlueteethDevice();
                    } else if (blueCommandType.equals("5")) {
                        defenseCloseBlueteethDevice();
                    } else if (blueCommandType.equals("6")) {

                    } else if (blueCommandType.equals("7")) {
                        restartBlueteethDevice();
                    } else if (blueCommandType.equals("8")) {
                        electricAccBlueteethDevice();
                    } else if (blueCommandType.equals("9")) {
                        electricAccCloseBlueteethDevice();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast( "蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 102) {
            String imel = data.getStringExtra("IMEI");
            inputImel.setText(imel);
            getDeviceCommandToken(imel);

        }
    }

    //获取token
    private void getDeviceCommandToken(String imel) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("username", imel);
        jsonObject.addProperty("password", "123456");
        jsonObject.addProperty("type", "3");
        XHttpRequest.getInstance().postRequest(Url.DEVICE_TOKEN, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.put("username", jsonObject.optJSONObject("data").optString("username"));
                                spUtils.put("devicetoken", jsonObject.optJSONObject("data").optString("token"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));

                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                spUtils.clear();
                                SharedUtil.setToken("");
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //寻车蓝牙命令
    private void findCarBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x04, new Byte[]{0x01}, new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");
                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }


    //电门开启蓝牙命令
    private void electricDoorBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x02, new Byte[]{0x00}, new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");
                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                    }
                });

    }


    //电门关闭蓝牙命令
    private void electricDoorCloseBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x02, new Byte[]{0x01},new SimpleCommonCallback(new ResultCallback() {
            @Override
            public void onResult(int resultCode){
                if (resultCode == 0) {
                    ToastUtil.showToast("发送蓝牙指令成功");
                } else {
                    ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                }
            }
        }));
    }



    //设防开启蓝牙命令
    private void defenseBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x01}, new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");
                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }


    //撤防蓝牙命令
    private void defenseCloseBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x00}, new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");
                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }


    //电池仓开启蓝牙命令
    private void electricAccBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x05, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");
                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }


    //电池仓关闭蓝牙命令
    private void electricAccCloseBlueteethDevice() {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x05, new Byte[]{0x00}, new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");
                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                    }
                });

    }

    //蓝牙重启
    private void restartBlueteethDevice() {
        TbitBle.commonCommand((byte) 0xFC, (byte) 0x02, new Byte[]{0x00}, new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                       dismissLoadingDialog();
                        if (resultCode == 0) {
                            ToastUtil.showToast("发送蓝牙指令成功");

                        } else {
                            ToastUtil.showToast("发送蓝牙指令失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        TbitBle.destroy();
        TbitBle.cancelAllCommand();
    }
}
